#include "wifiscanner.h"
#include "qtconcurrentrun.h"
#include "source/logger.h"
#include <QProcess>
#include <QRegularExpression>
#include <QDebug>
#include <QThread>
#include "popupmanager.h"

WiFiScanner &WiFiScanner::getInstance()
{
    static WiFiScanner _instance;
    return _instance;
}

WiFiScanner::WiFiScanner(QObject *parent) : QObject(parent), m_connectionStatus("未连接") {

    updateIpAddress();
}

QStringList WiFiScanner::wifiList() {
    return m_wifiList;
}

QString WiFiScanner::connectionStatus() {
    return m_connectionStatus;
}

QString WiFiScanner::ipAddress()
{
    return m_ipAddress;
}

void WiFiScanner::scanWiFi() {
    QtConcurrent::run([this]() {
        QProcess process;

        LogDebug << "WiFiScanner::scanWiFi ";
        PopupManager::instance().showPopup("正在搜索WIFI", "请稍后");
        // 运行 nmcli device wifi rescan 刷新 WiFi 列表
        process.start("sudo nmcli device wifi rescan");
        process.waitForFinished();
        QString rescanOutput = process.readAllStandardOutput();
        qDebug() << "Rescan output:" << rescanOutput;

        // 运行 nmcli dev wifi list 获取 WiFi 列表
        process.start("sudo nmcli -f SSID,SIGNAL dev wifi list");
        process.waitForFinished();
        QString output = process.readAllStandardOutput();

        QStringList lines = output.split('\n');
        QStringList wifiList;
        QVector<QPair<int, QString>> wifiPairs;

        QRegularExpression re(R"((.*)\s+(\d+)\s*$)");
        for (const QString &line : lines) {
            if (line.contains("SSID")) continue;

            QRegularExpressionMatch match = re.match(line);
            if (match.hasMatch()) {
                QString ssid = match.captured(1).trimmed();
                int signalStrength = match.captured(2).toInt();

                if (ssid != "--") {  // 过滤掉隐藏 WiFi
                    wifiPairs.append(qMakePair(signalStrength, ssid + " (" + QString::number(signalStrength) + "%)"));
                }
            }
        }

        std::sort(wifiPairs.begin(), wifiPairs.end(), std::greater<QPair<int, QString>>());

        for (const auto &pair : wifiPairs) {
            wifiList.append(pair.second);
        }

        //qDebug() << "wifiPairs:" << wifiList;
        if (m_wifiList != wifiList) {
            m_wifiList = wifiList;
            emit wifiListChanged();
        }
        updateConnectionStatus();
        PopupManager::instance().hidePopup();
    });
}

void WiFiScanner::connectToNetwork(const QString &ssid, const QString &password) {
    QtConcurrent::run([this, ssid, password]() {
        PopupManager::instance().showPopup("正在设置密码", "请稍后");
        QProcess process;
        QStringList arguments;
        arguments << "nmcli" << "dev" << "wifi" << "connect" << ssid << "password" << password;
        qInfo() << "Executing command: sudo" << arguments.join(" "); // 调试信息
        process.start("sudo", arguments);
        process.waitForFinished();
        QString output = process.readAllStandardOutput();
        QString errorOutput = process.readAllStandardError();

        qInfo() << "Command output:" << output; // 调试信息
        qInfo() << "Command error output:" << errorOutput; // 调试信息

        bool success = output.contains("successfully activated");
        if (success) {
            emit clearConnectionStatus(); // 清除所有 WiFiBox 的连接状态
        }
        emit connectionResult(success, ssid); // 传递SSID参数

        updateConnectionStatus();
        PopupManager::instance().hidePopup();
    });
}



void WiFiScanner::updateConnectionStatus() {
    QProcess process;
    process.start("nmcli connection show --active");
    process.waitForFinished();
    QString output = process.readAllStandardOutput();

    qDebug() << "Active connections:" << output;

    process.start("ip -4 addr show");
    process.waitForFinished();
    QString outputIP4  = process.readAllStandardOutput();

    qDebug() << "Active connections IP4:" << outputIP4;

    QStringList lines = output.split('\n');
    QString connectedWifi = "未连接";
    for (const QString &line : lines) {
        if (line.contains("wifi")) {
            QStringList parts = line.split(QRegularExpression("\\s+"), QString::SkipEmptyParts);
            if (parts.size() > 3) {
                connectedWifi = parts[0];
                break;
            }
        }
    }
    updateIpAddress();
    if (m_connectionStatus != connectedWifi) {
        m_connectionStatus = connectedWifi;
        emit connectionStatusChanged();
    }
}

void WiFiScanner::updateIpAddress()
{
    QProcess process;
    process.start("ip -4 addr show");
    process.waitForFinished();
    QString output = process.readAllStandardOutput();
    qDebug() << "Active connections IP4:" << output;
    m_ipAddress = "";
    QStringList lines = output.split('\n');
    QString ip;
    QRegularExpression re(R"(inet\s+(\d+\.\d+\.\d+\.\d+)/\d+\s+brd\s+\d+\.\d+\.\d+\.\d+\s+scope\s+global\s+dynamic\s+noprefixroute\s+(p2p0|wlan0))");

    for (const QString &line : lines) {
        QRegularExpressionMatch match = re.match(line);
        if (match.hasMatch()) {
            ip = match.captured(1);
            qDebug() << "Matched IP:" << ip << "for interface:" << match.captured(2);
            break;
        }
    }

    if (!ip.isEmpty() && m_ipAddress != ip) {
        m_ipAddress = ip;
        qDebug() << "IP address updated to:" << m_ipAddress;
    } else if (ip.isEmpty()) {
        qDebug() << "No valid IP address found for p2p0 or wlan0.";
    }
    emit ipAddressChanged();
}
